package org.simpleProxy;
import java.io.File;
import java.io.IOException;

import org.apache.ftpserver.ftplet.DefaultFtplet;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.FtpRequest;
import org.apache.ftpserver.ftplet.FtpSession;
import org.apache.ftpserver.ftplet.FtpletResult;
import org.apache.log4j.Logger;


/*
 * This class needs to override the upload mechanism to give the file
 * name and descriptor of the class. We'll just leave the file in the root directory, 
 * since we will delete it and use apache commons to forward it to the real FTP server.
 * 
 * In the meantime, we use lucene to parse whatever text is in the document, and use the extension
 * to determine where we will store the document
 */
public class LuceneFTPlet extends DefaultFtplet {

	public static Logger logger = Logger.getLogger(LuceneFTPlet.class.getName());
	public final String ftpFolder;
	
	public LuceneFTPlet(String ftpFolder) {
		this.ftpFolder = ftpFolder;
	}
	
	@Override
	public FtpletResult onUploadEnd(FtpSession session, FtpRequest request)
			throws FtpException, IOException {
		
		//Parse the FTP request for the fileName
		String fileName = request.getArgument();
		logger.info("Received object: " + fileName);
		
		//Get the CWD
		String path = new File(".").getAbsolutePath();
		
		//append it to the directory we are using for ftp - TODO: make this configurable
		File f = new File(path.substring(0, path.length()-1) + ftpFolder + "\\" + fileName);
		
		if(!f.exists()){
			logger.warn(f.getAbsolutePath() + " does not exist!");
		}
		else if(!f.canRead()){
			logger.warn(f.getAbsolutePath() + "is not readable...");
		}
		else {
			FilenameContainer container = new FilenameContainer();
			try {
				container.put(f.getAbsoluteFile().toString());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				logger.error("Could not add the file to fielHandler: " + f.getAbsolutePath());
			}
			container = null;
		}
		
		//return to superclass
		return super.onUploadEnd(session, request);
	}
}
